package Test01;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2023-07-15
 * Time: 19:21
 */
public class copyAll {
    public static void main(String[] args) {
        File srcFile=new File("E:\\javacode");
        File desFile=new File("D:\\");
        copyDir(srcFile,desFile);
    }
    /*
        srcFile拷贝源
        desFile拷贝目录
     */

    private static void copyDir(File srcFile, File desFile) {
        if (srcFile.isFile()){
            //srcFile是一个文件则递归结束
            //是文件的时候需要拷贝
            //一边读  一边写
            FileInputStream fileInputStream=null;
            FileOutputStream fileOutputStream=null;
            try {
                fileOutputStream=new FileOutputStream(srcFile);//读这个文件
                String path=(desFile.getAbsolutePath().endsWith("\\") ? desFile.getAbsolutePath():desFile.getAbsolutePath()+"\\")+desFile.getAbsolutePath().substring(3);
                fileOutputStream=new FileOutputStream(path);//
                byte[] bytes=new byte[1024 * 1024];
                int readCount=0;
                while ((readCount=fileInputStream.read(bytes))!=-1){
                    fileOutputStream.write(bytes,0,readCount);
                }
                fileOutputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fileInputStream!=null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fileOutputStream!=null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return;
        }
        File[]files= srcFile.listFiles();//获取源目录下的子目录
        for (File file:files) {
            //System.out.println(file.getAbsoluteFile());//获取所有文件的(包括目录和文件)绝对路径
            if (file.isDirectory()){
                //新建对应目录
                //System.out.println(file.getAbsoluteFile());
                String srcDir=file.getAbsolutePath();
                //System.out.println(srcDir.substring(3));
                String decDir=(desFile.getAbsolutePath().endsWith("\\") ? desFile.getAbsolutePath():desFile.getAbsolutePath()+"\\")+srcDir.substring(3);
                //System.out.println(decDir)
                //E:\javacode\Better   源目录
                //D:\javacode\Better   目标目录
                File file1=new File(decDir);
                if (!file1.exists()){
                    file1.mkdirs();
                }
            }
            copyDir(file,desFile);
        }

        //System.out.println(files.length);
    }
}
